<template>
  <div>
    <input type="file" @change="onChange" />
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { getFileChunksAndHash } from "./utils";

const onChange = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]!;

  const { chunkList, hash } = await getFileChunksAndHash(file);

  return;

  // 查询操作
  // const {
  //   data: { data: isUploaded },
  // } = await axios.post("/api/uploadSearch", {
  //   md5: hash,
  // });

  // console.log("isUploaded", isUploaded);
  // if (isUploaded) {
  //   return;
  // }

  console.time("upload");

  // 初始化上传
  const {
    data: { data: uploadId },
  } = await axios.post("/api/uploadInit", {
    name: file.name,
  });

  const promises = [];
  // 上传切片
  for (let i = 0; i < chunkList.length; i++) {
    promises.push(
      axios.post(
        "/api/uploadPart",
        {
          uploadId,
          partFile: chunkList[i],
          partIndex: i,
        },
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      )
    );
  }

  await Promise.all(promises);

  // 通知合并
  const {
    data: { data: path },
  } = await axios.post("/api/uploadComplete", {
    uploadId,
    name: file.name,
    md5: hash,
  });

  console.timeEnd("upload");
  console.log("完成", path);
};
</script>
